package com.xxx.proj.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xxx.proj.entity.Article;
import com.xxx.proj.entity.PageBean;
import com.xxx.proj.mapper.ArticleMapper;
import com.xxx.proj.service.ArticleService;
import com.xxx.proj.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Override
    public void add(Article article) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //创建PageBean对象
        PageBean<Article> pb = new PageBean<>();
        //开启分页查询
        PageHelper.startPage(pageNum,pageSize);

        //调用Mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as= articleMapper.list(categoryId,state,userId);
        //page中提供了方法,可以获取pagehelper分页查询后,得到总记录条数和当前页数
        Page<Article> p = (Page<Article>) as;

        //把数据填充到pageBean中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void update(Article article) {

        article.setUpdateTime(LocalDateTime.now());
        articleMapper.updateArticle(article);

    }

    @Override
    public void delete(Integer id) {
        articleMapper.delArticleById(id);
    }
}
